package com.ftwj.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftwj.entity.SysRole;
import com.ftwj.mapper.SysMenuListMapper;
import com.ftwj.mapper.SysRoleMapper;
import com.ftwj.service.SysRoleService;
import com.ftwj.vo.UserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysMenuListMapper sysMenuListMapper;
    @Override
    public List<SysRole> getRoleByRoleName(String roleName) {
        // 调用Mapper方法，传入角色名进行查询
        return sysRoleMapper.selectByRoleName(roleName);
    }

    @Override
    public boolean addRole(SysRole role) {
        // 验证角色名是否为空
        if (StringUtils.isBlank(role.getRoleName())) {
            throw new IllegalArgumentException("角色名(roleName)不能为空");
        }

        // 验证角色名是否重复
        List<SysRole> existingRole = this.getRoleByRoleName(role.getRoleName());
        if (existingRole != null) {
            throw new IllegalStateException("角色名已存在");
        }
        role.setCreateTime(DateTime.now());
        role.setUpdateTime(DateTime.now());
        return super.save(role);
    }

    @Override
    public boolean updateRole(SysRole role) {
        role.setUpdateTime(DateTime.now());
        return super.updateById(role);
    }

    @Override
    public boolean deleteRole(String id) {

        return super.removeById(id);
    }
    @Override
    public PageInfo<SysRole> getAllRoles(int pageNumber, int pageSize) {
        // 首先，获取总的记录数
        long total = sysRoleMapper.getTotalCount();
        // 设置分页参数
        PageHelper.startPage(pageNumber, pageSize);
        // 执行查询
        List<SysRole> roles = sysRoleMapper.getAllRoles();
        // 处理角色菜单关联
        for (SysRole role : roles) {
            role.setMenu(sysMenuListMapper.findMenuByRoleId(role.getId()));
        }
        // 创建PageInfo对象，手动设置total值
        PageInfo<SysRole> pageInfo = new PageInfo<>(roles);
        // 设置总记录数
        pageInfo.setTotal(total);
        return pageInfo;
    }

}

